import logging
import re

from flask import jsonify, request

from iHome import db
from iHome.api_1_0 import api
from iHome.models import User, House
from iHome.utils import qiniu_key
from iHome.utils.commons import login_required
from iHome.utils.image import storage


@api.route('/users/', methods=['GET'])
def get_user_profile():
    user_id = 1
    user = User.query.filter_by(id=user_id).first()
    data = {
        'name': user.name,
        'mobile': user.mobile,
        'id': user.id,
    }

    return jsonify(errno='0', errmsg='ok', data=data)


"""
修改用户头像
/users/avatars/   POST
用户头像，文件流   request.file.get('文件名').read()
调用七牛云上传图片接口 from iHome.utils.image import storage

"""


@api.route('/users/avatars/', methods=['POST'])
# @login_required
def upload_avatar():
    """
    上传用户头像
    1.取到客户端上传的文件,并判断
    2.使用七牛上传文件
    3.更新当前用户头像地址信息
    4.返回用户头像地址
    :return:
    """

    # 1.取到客户端上传的文件,并判断
    try:
        # avatar_file = request.files.get("avatar")
        avatar_file = request.files["avatar"]
        avatar_data = avatar_file.read()
    except Exception as e:
        # current_app.logger.error(e)
        return jsonify(errno='4001', errmsg="传入参数有误")

    """获取avatar的名字"""
    print(avatar_file.filename)

    # 2.使用七牛上传文件
    try:
        image_name = storage(avatar_data, avatar_file.filename)
    except Exception as e:
        # current_app.logger.error(e)
        return jsonify(errno='4001', errmsg='上传头像失败')

    # 3.更新当前用户头像地址信息
    user_id = 6
    try:
        User.query.filter_by(id=user_id).update({'avatar_url': image_name})
        db.session.commit()
    except Exception as e:
        # current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno='4101', errmsg='图片保存失败')
    else:
        # 4.返回用户头像地址
        avatar_url = qiniu_key.qiniu_html + image_name
        return jsonify(errno='0', errmsg='图片上传成功', data={"avatar_url": avatar_url})


"""修改用户名"""
"""
前端传用户名  name  
put  /users/names/
响应： 0修改成功  4001参数错误   4101用户未登录
"""


@api.route('/users/names/', methods=['PUT'])
def upgrade_user_name():
    user_id = 1

    name = request.json.get('name')

    if name is None:
        return jsonify(errno='4001', errmsg='用户名不能为空')

    user = User.query.filter_by(id=user_id).first()

    try:
        user.name = name
        db.session.commit()
    except Exception as e:
        logging.error(e)
        return jsonify(errno='4001', errmsg='修改用户名失败')

    return jsonify(errno='0', errmsg='修改用户名成功')


"""
用户实名认证
"""


@api.route('/users/auth/', methods=['POST'])
# @login_required
def set_auth():
    """
    实名认证
    :return:
    """
    # 1.获取服务器数据并判断
    json_dict = request.json
    real_name = json_dict['real_name']
    id_card = json_dict['id_card']
    if not all([real_name, id_card]):
        return jsonify(errno='4001', errmsg='参数错误')
    if not re.match('/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/', id_card):
        return jsonify({'errno': 402, 'errmsg': '身份证不完整'})
    # 2.获取当前用户的模型并更新认证信息
    # user_id = g.user_id
    user_id = 1
    try:
        User.query.filter_by(id=user_id).update({'real_name': real_name, 'id_card': id_card})
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno='4001', errmsg='认证信息保存失败')
    else:
        return jsonify(errno="0", errmsg='认证信息保存成功')


@api.route('/users/auth/', methods=['GET'])
def get_auth():
    user_id = 1

    user = User.query.filter_by(id=user_id).first()

    return jsonify({
        'errno': '0',
        'data': {
            'real_name': user.real_name,
            'id_card': user.id_card
        }

    })


@api.route('/users/houses/', methods=['GET'])
def get_house():
    user_id = 1
    house = House.query.filter_by(user_id=user_id)

    house_list = []

    for h in house:
        house_list.append(h.to_basic_dict())

    return jsonify(data=house_list, errno='0')
















